import configWifi from "@/pages/configDevice/models/configWifi";
import { bindDevice, getUserDeviceList } from "@/services/aepDeviceApi";
import { reportStopConfigWifiEvent } from "@/services/aggregateData";
import { addHome, getHomeList } from "@/services/home";
import { removeReceiveShareDevices } from "@/services/share";
import { checkName, isSameDevice } from "@/utils";
import SDK from "@/utils/SDK";
import Toast from "@/utils/Toast";
import i18n from "i18n-js";
import { action, computed, makeAutoObservable, runInAction, toJS } from "mobx";
import { persist } from "mobx-persist";
import deviceListModel from "./deviceList";
import deviceShareModel from "./deviceShare";
import alarmPush from "./alarmPush";

export interface IHomesModal {
  data: IHome[];
  initUserHomeInfo(): any;
  deleteDevice(device: IDevice): any;
  renameDevice({ device, name }: { device: IDevice; name: string }): any;
  cleanData(): void;
}

class Homes implements IHomesModal {
  constructor() {
    makeAutoObservable(this);
  }

  @persist("list") data: IHome[] = [];

  @persist current: number = 0;

  @computed get curHome() {
    const currentHome = this.data.find((item) => item.id === this.current);
    return currentHome;
  }

  @computed get homeDevices() {
    const currentHome = toJS(
      this.data.find((item) => item.id === this.current)
    );
    if (currentHome) {
      // tslint:disable-next-line: no-shadowed-variable
      const deviceList: IDevice[] = toJS(deviceListModel.data);
      const newDeviceList: IDevice[] = [];
      (currentHome.rooms || []).map((roomItem) => {
        roomItem.devices.map((deviceItem) => {
          deviceList.map((dataItem) => {
            if (dataItem.sno === deviceItem.sno) {
              newDeviceList.push({
                ...dataItem,
                roomName: roomItem.default ? i18n.t("DEFAULT") : roomItem.name,
                roomId: roomItem.id,
              });
            }
          });
        });
      });
      return newDeviceList;
    }
    return [];
  }

  @action.bound
  async initUserHomeInfo() {
    const data = await getHomeList();
    if (data.success) {
      console.log("data", data.data);
      const homeList = (data.data as IHome[]).map((item) => ({
        ...item,
      }));

      // 更新数据到homes
      runInAction(() => {
        this.data = homeList;
        let currentHome = this.data.find((item) => item.id === this.current);
        if (!currentHome && this.data.length > 0) {
          // 找不到的话就默认选择第一个 是主人的家庭
          currentHome = this.data.find((item) => item.owner == true);
          this.current = currentHome?.id as number;
        }
      });

      // 更新服务器设备列表
      runInAction(async () => {
        console.log("home触发服务器设备列表更新");
        // let devices: any = [];
        // homeList.map((home) =>
        //   (home.rooms || []).map((room) => {
        //     if (room.devices && room.devices.length > 0) {
        //       devices = devices.concat(room.devices);
        //     }
        //   })
        // );
        const res = await getUserDeviceList()
        if (res.success) {
          deviceListModel.updateServiceDeviceList(res.data);
        }
      });
    }
    return data;
  }

  @action
  async initHomes() {
    const res = await this.initUserHomeInfo();
    if (res.success) {
      const list = res.data;
      if (list.length < 1) {
        // 没有家庭就新建一个
        const params = {
          name: "我的家",
          address: "",
          wallpaper: "./static/bg_a_x@3x.e7cfdbc7.jpg",
          bgColor: "rgb(89,135,139)",
        };
        const addRes = await addHome(params);
        if (addRes.success) {
          await this.initUserHomeInfo();
        }
      }
    }
  }

  @action
  getDeviceHome(device: IDevice) {
    // 确保设备有roomId
    const serDevice = deviceListModel?.serviceDeviceList?.find((i) =>
      isSameDevice(i, device)
    );
    const home = this.data.find(
      (h) =>
        h.rooms &&
        h.rooms.findIndex((room) => room.id == serDevice?.roomId) > -1
    );
    if (home) {
      return home;
    }
    return null;
  }

  @action
  checkDeviceOwner(device: IDevice) {
    const home = this.getDeviceHome(device);
    if (home) {
      return home.owner;
    }
    return true;
  }

  @action
  deleteReceiveShareDevices(devices: IDevice[]) {
    if (devices.length === 0) {
      return { success: true };
    }
    return removeReceiveShareDevices(devices.map(d => ({ mac: d.mac, productKey: d.productKey })))
  }

  @action
  deleteDevices(devices: IDevice[]) {
    // const ownerDevices: IDevice[] = [];
    // const receiveShareDevices: IDevice[] = [];
    // const deviceNum = devices.length;
    // for (let i = 0; i < deviceNum; i++) {
    //   const d = devices[i];
    //   if (deviceShareModel.receiveList.find((r) => isSameDevice(r, d))) {
    //     receiveShareDevices.push(d);
    //   } else {
    //     ownerDevices.push(d);
    //   }
    // }
    return Promise.all([
      ...devices.map(d => this.deleteDevice(d)),
      // this.deleteReceiveShareDevices(receiveShareDevices)
    ])
  }

  @action
  async deleteDevice(device: IDevice) {
    return deviceListModel.unbindDevice({
      device,
      homeId: 0
    });
  }

  @action
  async renameDevice({
    device,
    name,
    refreshHomes = true,
  }: {
    device: IDevice;
    name: string;
    refreshHomes?: boolean;
  }) {
    let data = await deviceListModel.renameDevice({ device, name });
    return data;
  }

  @action
  async addDevice({ device }: { device: IDevice }) {
    // aep绑定不会通知到m2m会导致socket订阅问题，先调用openapi绑定
    const needRollback = deviceListModel.sdkDeviceList.findIndex(i => isSameDevice(i, device)) < 0;
    const openApiRes = await SDK.bindRemoteDevice(device);
    console.log('openApiResopenApiRes', openApiRes)
    if (openApiRes.success) {
      const room = this.curHome?.rooms[0];
      console.log('addDevice', room);
      const params = {
        mac: device.mac.toUpperCase(),
        productKey: device.productKey,
        roomId: room!.id,
        homeId: toJS(this.current),
      };
      if (device.name) {
        params.name = device.name;
      }
      // console.log('addDevice', params);
      const data = await bindDevice(params as IDevice);
      if (!data.success && needRollback) {
        // aep绑定失败的话，且本来就没绑定的话，调一次解绑
        SDK.unbindDevice([device]);
      }
      if (data.success) {
        alarmPush.subscribesDeviceWXMessage(device)
      }

      configWifi.eventID &&
        reportStopConfigWifiEvent({
          devices: [device],
          paasRes: openApiRes,
          saasRes: data,
          sdkRes: configWifi.sdkResCache,
        });
      return data;
    } else {
      configWifi.eventID &&
        reportStopConfigWifiEvent({
          devices: [device],
          paasRes: openApiRes,
          saasRes: {},
          sdkRes: configWifi.sdkResCache,
        });
      return openApiRes;
    }
  }

  @action
  cleanData() {
    this.data = [];
  }
}

const homes = new Homes();

const Home_Store_Key = "homes";

export { Homes, Home_Store_Key };

export default homes;
